﻿using System.Web;
using System.Web.Routing;

namespace ClassLibrary1
{
    public class RestRouteHandler<T> : IRouteHandler where T : RestHttpHandler, new()
    {
        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            return new T()
                       {
                           RouteData = requestContext.RouteData
                       };
        }
        public static void Register(string name, string pluralName)
        {
            RouteTable.Routes.Add(
                name,
                new Route(
                    string.Format(
                        "rest/{0}/{{{1}}}",
                        name,
                        RestHttpHandler.ParamKeyId
                        ),
                    new RestRouteHandler<T>()
                    )
                    {
                        Defaults = new RouteValueDictionary { { RestHttpHandler.ParamKeyId, null } },
                        Constraints = new RouteValueDictionary { { RestHttpHandler.ParamKeyId, "\\d*" } }
                    }
                );
            RouteTable.Routes.Add(
                pluralName,
                new Route(
                    string.Format(
                        "rest/{0}/{{*{1}}}",
                        pluralName,
                        RestHttpHandler.ParamKeyQuery
                        ),
                    new RestRouteHandler<T>())
                    {
                        Defaults = new RouteValueDictionary { { RestHttpHandler.ParamKeyQuery, "" } }
                    }
                );
        }
    }
}
